package com.qf.flashlib.base;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.widget.CustomProgressDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.ButterKnife;

/**
 * Fragment预加载问题的解决方案：
 * 1.可以懒加载的Fragment
 * 2.切换到其他页面时停止加载数据（可选）
 */

public abstract class LazyBaseFragment extends Fragment implements IView {
    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;
    public View view;
    private List<BasePresenter> mPresenters = new ArrayList<>();
    private CustomProgressDialog mLoadingDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view != null)
            return view;
        view = inflater.inflate(setContentView(), null);
        ButterKnife.bind(this, view);
        isInit = true;
        if (useEvent()) {
            EventBus.getDefault().register(this);
        }
        initInject();
        initView();
        /* 初始化的时候去加载数据 */
        isCanLoadData();
        return view;
    }

    protected boolean useEvent() {
        return false;
    }


    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    protected void initPresenters(BasePresenter... presenter) {
        if (presenter.length > 0) {
            Collections.addAll(mPresenters, presenter);
        }
        for (BasePresenter mPresenter : mPresenters) {
            mPresenter.attachView(this);
        }
    }


    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit)
            return;

        if (getUserVisibleHint()) {
            if (!isLoad)
                lazyLoad();
            isLoad = true;
        } else if (isLoad) {
            stopLoad();
        }
    }

    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
        for (BasePresenter mPresenter : mPresenters) {
            mPresenter.detachView();
        }
        if (useEvent()) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 设置Fragment要显示的布局
     *
     * @return 布局的layoutId
     */
    protected abstract int setContentView();

    /**
     * 获取设置的布局
     *
     * @return
     */
    protected View getContentView() {
        return view;
    }

    /**
     * 初始化注入
     */
    protected void initInject() {
    }

    /**
     * 初始化事件
     */
    protected abstract void initView();

    /**
     * 当视图初始化并且对用户可见的时候去真正的加载数据
     */
    protected abstract void lazyLoad();

    /**
     * 当视图已经对用户不可见并且加载过数据，如果需要在切换到其他页面时停止加载数据，可以覆写此方法
     */
    protected void stopLoad() {
    }


    /* 展示加载中对话框 */
    public void showLoadingDialog(String tip, boolean cancelable)
    {
        if (mLoadingDialog == null) {
            mLoadingDialog = new CustomProgressDialog(getActivity());
            mLoadingDialog.setCanceledOnTouchOutside(false);
            mLoadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
            {
                @Override
                public void onCancel(DialogInterface dialog)
                {
                }
            });
        }
        mLoadingDialog.setTipText(tip);
        mLoadingDialog.setCancelable(cancelable);
        if (!mLoadingDialog.isShowing())
            mLoadingDialog.show();

    }

    /* 展示加载中对话框 */
    public void showLoadingDialog()
    {
        this.showLoadingDialog("请稍候...", true);
    }

    /* 关闭对话框 */
    public void dismissLoadingDialog()
    {
        if (mLoadingDialog != null && mLoadingDialog.isShowing())
            mLoadingDialog.dismiss();
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }


    @Override
    public void showMessage(String msg) {
        FlashLib.showToast(msg);
    }

    @Override
    public void onError(ApiException e) {

    }
}